package com.hcloud.libupload.utils

import android.util.Base64
import java.io.UnsupportedEncodingException
import java.math.RoundingMode
import java.net.URLEncoder
import java.text.DecimalFormat
import kotlin.math.pow

object PanUtil {

    fun getUploadAuth(boxId: String, loginKey: String, phone: String): String {
        val pwd = "$loginKey,$phone"
        val user = "$boxId:$pwd".toByteArray()
        return "Basic " + Base64.encodeToString(user, Base64.NO_WRAP)
    }


    fun getRequestId(phone: String = ""): String {
        return "$phone${System.currentTimeMillis()}${(0..9).random()}00000${(0..9).random()}"
    }

    fun getAuth(boxId: String, psw: String): String {
        val user = "1$boxId:$psw"
        val bytes = user.toByteArray()
        val base64 = Base64.encodeToString(bytes, Base64.NO_WRAP)
        val stringBuilder = StringBuilder(base64)
        stringBuilder.insert(16, 1)
        return stringBuilder.toString()
    }


    fun getUrlEncoder(path: String): String {
        var url = ""
        try {
            url = URLEncoder.encode(path, "utf-8")
            url = url.replace("\\+".toRegex(), "%20")
                .replace("%3A".toRegex(), ":")
                .replace("%2F".toRegex(), "/")
                .replace("%3F".toRegex(), "?")
                .replace("%3D".toRegex(), "=")
                .replace("%26".toRegex(), "&")
        } catch (e: UnsupportedEncodingException) {
            e.printStackTrace()
        }
        return url
    }

    fun score2dimensionality(string: String?): Double {
        var dimensionality = 0.0
        if (null == string) {
            return dimensionality
        }

        //用 ，将数值分成3份
        val split = string.split(",".toRegex()).toTypedArray()
        for (i in split.indices) {
            val s = split[i].split("/".toRegex()).toTypedArray()
            //用112/1得到度分秒数值
            val v = s[0].toDouble() / s[1].toDouble()
            //将分秒分别除以60和3600得到度，并将度分秒相加
            dimensionality += v / 60.0.pow(i.toDouble())
        }
        val format = DecimalFormat("0.######")
        //未保留小数的舍弃规则，RoundingMode.FLOOR表示直接舍弃。
        format.roundingMode = RoundingMode.FLOOR
        return format.format(dimensionality).toDouble()
    }
}